import React, {Component} from 'react';
import {connect} from "react-redux";
import {Dropdown, Button, Icon, Menu, Badge, Popconfirm, message} from "antd";
import {messages} from "share/common";
import Info from "components/info";
import Importer from "components/template/importer/index";
import SlideFrame from "components/slide-frame";
import ExportModal from "components/template/export-modal/export-modal";
import AdvancedTable from "components/advanced-table";
import Condition from "components/condition";
import antdCommon from "share/prototype-extend/antd-common";
import BlackWhiteDetail from "./detail";
import taxCodeService from "../tax-code.service"
import "styles/finance-setting/tax-code/black-white-list.scss"

const { SimpleTable } = AdvancedTable;
const { renderPopover } = antdCommon;
const { If } = Condition;

@connect(mapStateToProps)
class BlackWhiteList extends Component {

  state = {
    loading: false,
  };

  infoData = {
    attributes: [
      { title: messages('expense-14.key536')/*白名单*/, dataIndex: 'white', span: 24, widthFix: false },
      { title: messages('expense-14.key537')/*黑名单*/, dataIndex: 'black', span: 24, widthFix: false },
      { title: messages('expense-14.key538')/*灰名单（白名单和黑名单外的发票）*/, dataIndex: 'gray', span: 24, widthFix: false }
    ],
    dataSource: {
      white: messages('expense-14.key539')/*发票推荐报销相关的费用类型*/,
      black: messages('expense-14.key540')/*发票不可报销相关的费用类型*/,
      gray: messages('expense-14.key541')/*发票弱管控，保存费用后标记【发票不匹配】*/
    }
  };

  columns = [{
    dataIndex: 'levelCode',
    title: messages('expense-14.key312')/*层级*/,
    width: '10%',
    render: () => messages('expense-14.key321')/*租户*/
  }, {
    dataIndex: 'levelOrgName',
    title: messages('expense-14.key307')/*所属组织*/
  }, {
    dataIndex: 'listCode',
    title: messages('expense-14.key528')/*编码*/
  }, {
    dataIndex: 'listName',
    title: messages('expense-14.key529')/*名称*/,
    render: value => renderPopover(value)
  }, {
    dataIndex: 'listDesc',
    title: messages('expense-14.key530')/*描述*/,
    render: value => renderPopover(value)
  }, {
    dataIndex: 'listType',
    title: messages('expense-14.key542')/*名单类型*/,
    render: value => value === 'WHITE' ? messages('expense-14.key536')/*白名单*/ : messages('expense-14.key537')/*黑名单*/
  }, {
    dataIndex: 'enabled',
    title: messages('common.column.status')/*状态*/,
    width: '10%',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
      />
    )
  }, {
    dataIndex: 'expReceiptMappingListId',
    title: messages('common.operation')/*操作*/,
    render: (value, record) => record.readOnly ? '-' : (
      <Popconfirm onConfirm={() => this.handleDelete(value)} title={messages('common.confirm.delete')/*确定要删除吗？*/}>
        <a onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</a>
      </Popconfirm>
    )
  }];

  service = (page, size) => {
    return taxCodeService.getWhiteBlackList({ page, size });
  };

  handleRowClick = record => {
    this.handleOpenDetail(record.listType, record);
  };

  handleDelete = id => {
    this.setState({ loading: true });
    taxCodeService.deleteWhiteBlackItem(id)
      .then(() => {
        message.success(messages('common.delete.successful')/*删除成功*/);
        this.tableRef.getList();
      })
      .finally(() => {
        this.setState({ loading: false });
      })
  };

  handleMenuClick = e => {
    this.handleOpenDetail(e.key);
  };

  handleOpenDetail = (listType, record = {}) => {
    SlideFrame.open({
      title: listType === 'BLACK' ? messages('expense-14.key543')/*设置黑名单*/ : messages('expense-14.key544')/*设置白名单*/,
      content: BlackWhiteDetail,
      noPadding: true,
      params: {
        listType,
        record
      },
      afterClose: refresh => refresh === true && this.tableRef.getList()
    }, this)
  };

  handelImportCallBack = result => {
    let resultDom = null;
    if (result.success) {
      this.tableRef.getList();
      resultDom = <div>{messages('expense-14.key414')/*导入成功*/}</div>;
    } else {
      resultDom = (
        <div>
          <div style={{ marginBottom: 10 }}>
            {messages('expense-14.key415')/*导入失败*/}
          </div>
          {result.rows
            ? <a href={result.rows.fileURL}>{messages('expense-14.key416')/*下载错误文件*/}</a>
            : <span>{result.message}</span>
          }
        </div>
      );
    }
    return resultDom;
  };

  renderOverlayMenu = () => (
    <Menu onClick={this.handleMenuClick}>
      <Menu.Item key="WHITE">
        {messages('expense-14.key536')/*白名单*/}
      </Menu.Item>
      <Menu.Item key="BLACK">
        {messages('expense-14.key537')/*黑名单*/}
      </Menu.Item>
    </Menu>
  );

  render() {
    const { authPolicyAll } = this.props;
    const { loading } = this.state;
    return (
      <div className="black-white-list">
        <SimpleTable
          onRef={ref => this.tableRef = ref}
          rowKey="expReceiptMappingListId"
          loading={loading}
          columns={this.columns}
          service={this.service}
          tableName="black-white-list-table"
          show={['tag-list', 'table-utils']}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
        >
          <Info
            paragraph
            dataSource={this.infoData.dataSource}
            attributes={this.infoData.attributes}
          />
          <If value={authPolicyAll}>
            <div className="black-white-list-buttons">
              <Dropdown overlay={this.renderOverlayMenu()}>
                <Button type="primary">
                  {messages('common.add')/*添加*/}<Icon type="down"/>
                </Button>
              </Dropdown>

              <Importer
                btnProps={{ type: 'normal' }}
                templateOptions={{
                  templateList: [{
                    templateName: messages('expense-14.key417')/*下载Excel电子表格*/,
                    downloadUrl: '/api/exp/receipt/mapping/list/template/download',
                    downFileName: messages('expense-14.key545')/*发票黑白名单*/
                  }]
                }}
                uploadOptions={{ uploadUrl: '/api/exp/receipt/mapping/list/template/upload' }}
                errorTableData={this.handelImportCallBack}
              />

              <ExportModal
                type="btn"
                btnType="normal"
                exportTitle={messages('expense-14.key419')/*导出*/}
                exportType="EXPENSE_RECEIPT_MAPPING_LIST"
                exportCondition={{}}
                exportCommand="EXPENSE_RECEIPT_MAPPING_LIST"
              />
            </div>
          </If>
        </SimpleTable>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    authPolicyAll: state.main.authPolicyAll
  }
}

export default BlackWhiteList;
